package org.cangku.controller;

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.cangku.dao.SupplierDao;
import org.cangku.entity.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/supplier")
public class SupplierController{

    @Autowired
    private SupplierDao supplierDao;

    @RequestMapping("/getsupplier")
    @ResponseBody
    public List<Supplier> getSupplier(){
        return supplierDao.getIdAndName();
    }

    @RequestMapping("/query")
    @ResponseBody
    public Map<String,Object> query(String gname,String address,int offset,int limit){
        Map<String,Object> map = new HashMap<String, Object>();

        try {
            String name = new String(gname.getBytes("ISO-8859-1"),"utf-8");
            String dizhi = new String(address.getBytes("ISO-8859-1"),"utf-8");

            map.put("rows",supplierDao.query(name,dizhi,offset,limit));
            map.put("total",supplierDao.getQueryCount(name,dizhi));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return map;
    }

    @RequestMapping("/serch")
    @ResponseBody
    public Map<String,Object> serch(String gname,String address,int offset,int limit){
        Map<String,Object> map = new HashMap<String, Object>();

        map.put("rows",supplierDao.query(gname,address,offset,limit));
        map.put("total",supplierDao.getQueryCount(gname,address));

        return map;
    }

    @RequestMapping("/insert")
    @ResponseBody
    /*String name,String contacts,String phone,String address,String remarks*/
    public Map<String,Object> insert(Supplier supplier){
        Map<String,Object> map = new HashMap<String, Object>();

        supplierDao.InsertInfo(supplier);

        map.put("rows",supplierDao.query("","",0,9));
        map.put("total",supplierDao.getQueryCount("",""));

        return map;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map<String,Object> update(Supplier supplier){

        Map<String,Object> map = new HashMap<String, Object>();

        supplierDao.Update(supplier);

        map.put("rows",supplierDao.query("","",0,9));
        map.put("total",supplierDao.getQueryCount("",""));

        return map;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String ids){

        String[] id = ids.split(",");
        for(int i = 0;i<id.length;i++){
            supplierDao.delete(Integer.parseInt(id[i]));
        }

        Map<String,Object> map = new HashMap<String, Object>();

        map.put("rows",supplierDao.query("","",0,9));
        map.put("total",supplierDao.getQueryCount("",""));

        return map;
    }

    @RequestMapping("/getIdAndName")
    @ResponseBody
    public List<Supplier> getIdAndName(){
        return supplierDao.getIdAndName();
    }

    /*下载表格 */
    @RequestMapping(value = "/fileDownloadByDate")
    public ResponseEntity<byte[]> fileDownloadData(HttpServletRequest request, HttpServletResponse resp) throws Exception {
        //加载表的所有数据
        List<Supplier> list =  supplierDao.getIdAndName() ;
        //在服务器上产生excel数据表格
        XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(new File("供货商模板.xlsx"))) ;
        //得到excel表格的每个worksheet
        XSSFSheet sheet = xwb.getSheetAt(0);
        //声明行
        XSSFRow row = null;
        //单元格样式
        XSSFCellStyle style = xwb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        XSSFFont font = xwb.createFont();// 创建字体对象
        font.setFontHeightInPoints((short) 10);// 设置字体大小
        style.setFont(font);
        for (int i=0;i<list.size();i++) {
            Supplier supplier = list.get(i) ;
            row = sheet.createRow(i+1);
            //设置行高
            row.setHeight((short) 400);

            String id = Long.toString(supplier.getId());
            String gname = supplier.getGname() ;
            String contacts = supplier.getContacts();
            String phone  = supplier.getPhone() ;
            String address = supplier.getAddress() ;

            //设置单元格样式
            XSSFCell cell0 = row.createCell(1) ;
            cell0.setCellStyle(style);
            //设置单元格样式
            XSSFCell cell1 = row.createCell(2) ;
            cell1.setCellStyle(style);

            //设置单元格样式
            XSSFCell cell2 = row.createCell(3) ;
            cell2.setCellStyle(style);
            //设置单元格样式
            XSSFCell cell3 = row.createCell(4) ;
            cell3.setCellStyle(style);
            //设置单元格样式
            XSSFCell cell4 = row.createCell(5) ;
            cell4.setCellStyle(style);

            cell0.setCellValue(id);
            cell1.setCellValue(gname);
            cell2.setCellValue(contacts);
            cell3.setCellValue(phone);
            cell4.setCellValue(address);
        }
        //格式化当前时间
        String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) ;
        String fileName = "供货商数据"+strDate+".xlsx" ;
        //在服务器上生成数据
        FileOutputStream os = new FileOutputStream(fileName);
        xwb.write(os);
        os.close();// 关闭文件输出流

        byte[] body = null;
        File file = new File(fileName);
        InputStream in = new FileInputStream(file);
        body = new byte[in.available()];
        in.read(body);

        HttpHeaders headers = new HttpHeaders();
        String fname = new String(fileName.getBytes("gbk"), "iso8859-1");
        headers.add("Content-Disposition", "attachment;filename=" + fname);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        in.close();
        return response;
    }
}
